package org.lanqiao.api.user;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.lanqiao.common.Constants;
import org.lanqiao.common.JsonResult;
import org.lanqiao.common.JsonResultWriter;
import org.lanqiao.service.UserServiceImpl;
import org.lanqiao.util.StringUtil;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(description = "这是一个登录的接口", urlPatterns = { "/api/user/login" })
public class LoginUserNameServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginUserNameServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取参数
	    String userName = StringUtil.empty(request.getParameter("userName"));
		String password = StringUtil.empty(request.getParameter("password"));
		String code=StringUtil.empty(request.getParameter("code"));//验证码
		
		//创建一个JsonResult封装消息，然后转为json，变成一个对象{}
        JsonResult result=null;
        //获得当前请求的Session对象，如果上下文中没有绑定的Session，创建一个session，如果有就返回session
        HttpSession session=request.getSession();
        String sessionCode=((String)session.getAttribute("code"));
        List <HashMap<String,Object>>list=null;
        if(sessionCode==null||code==null||userName==null||!code.toLowerCase().equals(sessionCode.toLowerCase())) {
            result=new JsonResult<LinkedHashMap<String,Object>>("验证码或用户名疯狂赶来中",Constants.STATUS_FAILURE);
        }else {
                try {
                    UserServiceImpl usi=new UserServiceImpl();
                    list=usi.login(userName, password);
                    if(list.size()>0) {
                        result=new JsonResult ("登录成功",Constants.STATUS_SUCCESS, list);
                        //登录成功之后，把用户id，存入session
                        session.setAttribute("userId", StringUtil.empty(list.get(0).get("userId")) );
                    }else {
                        result=new JsonResult<LinkedHashMap<String,Object>>("用户名或密码错误",Constants.STATUS_UNFOUND);
                    }
                }catch(Exception ex){
                    result=new JsonResult ("查询异常",Constants.STATUS_FAILURE,ex.getMessage());
                }  
            }
        
        //将响应和结果  数据，转为json
        JsonResultWriter.writer(response, result);
	}
}

